<?php


class AdminController extends BaseController
{
    const admin_auth_session_key = 'auth_manager_user';
    protected $page_size = 20;
    protected $page = 1;
    public $user;
    protected $ispost;
    // 不用权限直接使用的
    private $allowAction = array(
        'admin/login/index',
        'admin/login/out',
        'admin/index/index',
        'admin/index/main',
        'admin/users/setpwd',
    );

    // 自动执行
    public function init()
    {
        parent::init();
        // 过校验
        // 检测登录
        $this->isLogin();
        // 检测权限
        $action = strtolower($this->getModuleName() . '/' . $this->request->getControllerName() . '/' . $this->request->getActionName());
        if (!in_array($action, $this->allowAction)) {
            // 检测用户google_secret
            if (empty($this->user['userinfo']->google_secret) && $this->config->google->authenticator) {
                $this->result('请先绑定Google随机验证码,再正常使用后台系统!');
            }
            if (!AdminUsersModel::check_right($action)) {
                $this->displayWarn('您没有操作的权限 ' . $this->request->getActionName());
            }
        }
        // 分页和每页数量
        if (intval($this->get('limit'))) $this->page_size = intval($this->get('limit'));
        if (intval($this->get('page'))) $this->page = intval($this->get('page'));
        $this->view->assign('application_name', $this->config->application->name);
        $this->view->assign('page_id',str_replace('/','_',$action));
    }

    // 操作日志记录
    protected function operation_log($title, $before_data = array(), $after_data = array())
    {
        $action = strtolower($this->getModuleName() . '/' . $this->request->getControllerName() . '/' . $this->request->getActionName());
        $operation_data = array(
            'userid' => $this->user['userinfo']->id,
            'username' => $this->user['userinfo']->username,
            'uri' => $action,
            'url' => 'http://' . $_SERVER['SERVER_NAME'] . ':' . $_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"],
            'operation_title' => $title,
            'time' => time(),
            'before_data' => json_encode($before_data, JSON_UNESCAPED_UNICODE),
            'after_data' => json_encode($after_data, JSON_UNESCAPED_UNICODE),
            'isdo' => 0
        );
        if (strpos($_SERVER["REQUEST_URI"], 'do=list') < 1) $operation_data['isdo'] = 1;
        AdminOperationLogsModel::create($operation_data);
    }

    protected function ajaxresult($code = 0, $msg = '', $data = array(), $plusparam = array())
    {
        $ajax_result = array(
            'code' => $code,
            'msg' => $msg,
            'data' => $data
        );
        unset($plusparam['code'], $plusparam['msg']);
        die(json_encode(array_merge($ajax_result, $plusparam), JSON_UNESCAPED_UNICODE));
    }

    /**
     * 检测是否登录
     */
    public function isLogin()
    {
        $user = $this->session->get(self::admin_auth_session_key);
        if ($user) {
            // 已登录
            $this->user = unserialize($user);
            // 检测登录IP
            if (!AdminUsersModel::checkOnlineUser($this->user['userinfo']->id)) {
                if (isset($_REQUEST['isajax']) && $_REQUEST['isajax'] == 1) {
                    $this->result('登录超时,请重新登录!');
                } else {
                    return header('location: /admin/login/index');
                }
            }
            $this->view->assign('adminuser', $this->user['userinfo']);
        } else {
            // 未登录
            $action = strtolower($this->getModuleName() . '/' . $this->request->getControllerName());
            if ($action != 'admin/login') {
                if (isset($_REQUEST['isajax']) && $_REQUEST['isajax'] == 1) {
                    $this->result('您未登录或登录已过期,请先登录在使用后台功能!');
                } else {
                    return header('location: /admin/login/index');
                }
            }
        }
    }

    protected function post($var, $default = null)
    {
        $value = $this->request->getPost($var);
        if (is_numeric($value)) return $value;
        if (is_array($value) && $value) return $value;
        if (is_string($value) && !empty($value)) return trim($value);
        return $default;
    }

    protected function get($var, $default = null)
    {
        $value = $this->request->getQuery($var);
        if (is_numeric($value)) return $value;
        if (is_array($value) && $value) return $value;
        if (is_string($value) && !empty($value)) return trim($value);
        return $default;
    }

    protected function _list($model, $parameters2 = [])
    {
        $parameters['limit'] = $this->page_size;
        $parameters = array_merge($parameters, $parameters2);
        // 搜索条件
        $query = $model::newQuery();
        //print_r($model);exit;
        foreach ($parameters['conditions'] as $k => $item) {
            if (is_array($item) && count($item) == 3) {
                $query->where($item[0], $item[1], $item[2]);
            } elseif (is_array($item) && count($item) == 2) {
                $query->where($item[0], $item[1]);
            } else {
                $query->where($k, $item);
            }
        }
        // 翻页
        $count = $query->count();
        if (isset($parameters['order'])) {
            if (is_array($parameters['order'])) {
                $query->order($parameters['order'][0], $parameters['order'][1]);
            } else {
                $query->order($parameters['order']);
            }
        };
        $data = $query->page($this->page, $parameters['limit'])->select();
        return array(
            'count' => $count,
            'data' => $data
        );
    }
}